    //
//  SearchViewController.m
//  Menu
//
//  Created by trimad on 11-11-27.
//  Copyright 2011 Trimad Group. All rights reserved.
//

#import "SearchViewController.h"
#import "Item.h"
#import "OrderItem.h"
#import "DisplayManager.h"
#import "OrderManager.h"
#import "ContextManager.h"
#import "MenuViewController.h"

@interface SearchViewController(Private) 
-(UITableViewCell *)drawSearchTableViewCell:(UITableViewCell *)cell item:(Item *)item 
								  indexPath:(NSIndexPath *)indexPath;
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
@end


@implementation SearchViewController

@synthesize theTableView;
@synthesize theSearchBar;

NSArray *searchResultItemArray;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	searchResultItemArray = [[DisplayManager instance] searchItems:@"*"];
	[[self.theSearchBar.subviews objectAtIndex:0]removeFromSuperview];
	self.theSearchBar.backgroundColor = [UIColor clearColor];
	self.theSearchBar.showsCancelButton = NO;
	UIColor *tableBackgroundColor = [UIColor colorWithRed:(CGFloat)247/255 
													green:(CGFloat)245/255 
													 blue:(CGFloat)234/255 
													alpha:(CGFloat)1.0];
	[self.theTableView setBackgroundColor:tableBackgroundColor];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (searchResultItemArray != nil) {
		return [searchResultItemArray count];
	} else {
		return 0;
	}
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
    self.theTableView.allowsSelection = NO;
    self.theTableView.scrollEnabled = NO;
	for (id aSubView in [searchBar subviews]) {
        if([aSubView isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)aSubView;
            [btn setTitle:@"关闭"  forState:UIControlStateNormal];
        }
    }
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
	self.theTableView.allowsSelection = YES;
	self.theTableView.scrollEnabled = YES;
	searchResultItemArray = [[DisplayManager instance] searchItems:searchText];
	[self.theTableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
	self.view.superview.hidden = YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *searchTableIdentifier = @"SearchTableIdentifier";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:searchTableIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
									  reuseIdentifier:searchTableIdentifier] autorelease];
	}
	cell = [self drawSearchTableViewCell:cell 
				item:[searchResultItemArray objectAtIndex:[indexPath row]]
				indexPath:indexPath];
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	Item *item = [searchResultItemArray objectAtIndex:indexPath.row];
	int pageIndex = [[DisplayManager instance] pageIndex:item.code];
	MenuViewController *menuVC=[[ContextManager getInstance] rootViewController];
	[menuVC jumpToPage:pageIndex];
}

- (UITableViewCell *)drawSearchTableViewCell:(UITableViewCell *)cell 
						item:(Item *)item 
					   indexPath:(NSIndexPath *)indexPath {
	UIColor *tableBackgroundColor = [UIColor colorWithRed:(CGFloat)247/255 
													green:(CGFloat)245/255 
													 blue:(CGFloat)234/255 
													alpha:(CGFloat)1.0];
	UIImage *thumbnail;
	if (item.largeImageName != nil && ![item.largeImageName isEqualToString:@""]) {
		thumbnail = [UIImage imageNamed:item.largeImageName];
	} else {
		thumbnail = [UIImage imageNamed:item.midImageName];
	}
	
	// thumb nail
	UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnail];
	CGRect thumbnailFrame = CGRectMake(10, 0, 40, 40);
	thumbnailImageView.frame = thumbnailFrame;
	[cell.contentView addSubview:thumbnailImageView];
	[thumbnailImageView release];
	
	// code
	CGRect codeLabelFrame = CGRectMake(80, 15, 120, 20);
	UILabel *codeLabel = [[UILabel alloc] initWithFrame:codeLabelFrame];
	codeLabel.text = item.code;
	codeLabel.textColor = [UIColor redColor];
	codeLabel.backgroundColor = tableBackgroundColor;
	[cell.contentView addSubview:codeLabel];
	[codeLabel release];
	
	// name
	CGRect nameLabelFrame = CGRectMake(150, 15, 120, 20);
	UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelFrame];
	nameLabel.text = item.name;
	nameLabel.backgroundColor = tableBackgroundColor;
	[cell.contentView addSubview:nameLabel];
	[nameLabel release];
	
	// add one
	UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(280, 10, 30, 30)];
	UIImage *addImage = [UIImage imageNamed:@"icon_+1_3.png"];
	[addButton setBackgroundImage:addImage forState:UIControlStateNormal];
	[addButton setTag:indexPath.row];
	[addButton addTarget:self action:@selector(addOneClicked:) forControlEvents:UIControlEventTouchUpInside];
	[cell.contentView addSubview:addButton];
	[addButton release];
	
	return cell;
}

-(void) addOneClicked:(id) sender {
	UIButton *addButton = (UIButton *)sender;
	NSInteger index = addButton.tag;
	Item *item = [searchResultItemArray objectAtIndex:index];
	OrderItem *orderItem = [[OrderManager getInstance] getOrderItem:item.code];
	if (orderItem == nil) {
		orderItem = [[OrderItem alloc] init];
		orderItem.item = item;
	}
	orderItem.quantity++;
	[[OrderManager getInstance] updateOrderItem:orderItem];
}

-(IBAction) closeButtonClicked:(id)sender {
	self.view.superview.hidden = YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
